package com.anlogic.sdk.toolpreference.utils;

import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.swt.events.TypedEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Text;
import org.osgi.service.prefs.BackingStoreException;

public class FlashPreferencesUtils {
	public static final String PLUGIN_ID = "com.anlogic.sdk.programflash";

	public static IEclipsePreferences getPreferences() {
		IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(PLUGIN_ID);
		return preferences;
	}

	public static void savePreferences(TypedEvent e) {
		IEclipsePreferences flashPrefs = getPreferences();
		Object obj = e.getSource();
		if (obj instanceof Combo) {
			Combo combo = (Combo) obj;
			String data = (String) combo.getData();
			if ("chipCombo".equals(data)) {
				int selectionIndex = combo.getSelectionIndex();
				flashPrefs.putInt("chipCombo", selectionIndex);
			} else if ("flashTypeCombo".equals(data)) {
				int flashTypeIndex = combo.getSelectionIndex();
				flashPrefs.putInt("flashTypeCombo", flashTypeIndex);

			}
		} else if (obj instanceof Text) {
			Text text = (Text) obj;
			String data = (String) text.getData();
			if ("imageFileText".equals(data)) {
				String image = text.getText();
				flashPrefs.put("imageFileText", image);
			} else if ("offsetText".equals(data)) {
				String offset = text.getText();
				flashPrefs.put("offsetText", offset);
			} else if ("bankId".equals(data)) {
				flashPrefs.put("bankId", text.getText());
			} else if ("readCmd".equals(data)) {
				flashPrefs.put("readCmd", text.getText());
			} else if ("pprogCmd".equals(data)) {
				flashPrefs.put("pprogCmd", text.getText());
			} else if ("eraseCmd".equals(data)) {
				flashPrefs.put("eraseCmd", text.getText());
			} else if ("pageSize".equals(data)) {
				flashPrefs.put("pageSize", text.getText());
			} else if ("sectorSize".equals(data)) {
				flashPrefs.put("sectorSize", text.getText());
			} else if ("chipSize".equals(data)) {
				flashPrefs.put("chipSize", text.getText());
			}

		} else if (obj instanceof Button) {
			Button button = (Button) obj;
			String data = (String) button.getData();
			if ("useCustomizeFlash".equals(data)) {
				flashPrefs.putBoolean("useCustomizeFlash", button.getSelection());
			} else if ("eraseFlashButton".equals(data)) {
				flashPrefs.putBoolean("eraseFlashButton", button.getSelection());
			} else if ("xipEnableButton".equals(data)) {
				flashPrefs.putBoolean("xipEnableButton", button.getSelection());
			} else if ("verifyButton".equals(data)) {
				flashPrefs.putBoolean("verifyButton", button.getSelection());

			}

		}
		try {
			flashPrefs.flush();
		} catch (BackingStoreException e1) {
			e1.printStackTrace();
		}
	}

}
